package com.aye.notepad.Activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.aye.notepad.DatabaseModel.Record;
import com.aye.notepad.DatabaseModel.User;
import com.aye.notepad.MyAdapter;
import com.aye.notepad.R;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private ListView listView,listView2;   //ListView
    private ImageView iv_add,iv_user;  //添加图片
    private MyAdapter myAdapter;
    private List<Record> resultList;
    private TextView tv_showName,tv_city,tv_temp,tv_weather;
    AlertDialog dialog;

    private static final String TAG = "MainActivity";
    private int userId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //数据初始化
        Intent intent=getIntent();
        userId= Integer.parseInt(intent.getStringExtra("userId"));
        String name=intent.getStringExtra("name");

        init();
        showMsg("欢迎您，"+name);
        tv_showName.setText(name);

/*************************************************add点击事件(添加记录)*****************************************/
        iv_add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent1=new Intent(MainActivity.this, RecordActivity.class);
                intent1.putExtra("userId",String.valueOf(userId));
                startActivityForResult(intent1,1);
            }
        });

/*************************************************listView单项点击事件(查询/修改记录)*****************************************/
        //设置列表项的点击监听器,点击触发，对相应内容进行更新
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //当列表项被点击时，对该项的内容进行修改操作
                Record record= (Record) myAdapter.getItem(position);
                //创建意图，将用户选中项的内容传递到修改的页面
                Intent intent=new Intent(MainActivity.this,RecordActivity.class);
                String sendId= String.valueOf(record.getId());
                String sendContent=record.getContent();
                String sendTime=record.getDate();
                String sendTitle=record.getTitle();
                Log.i(TAG, "onItemClick: "+record.toString());
                intent.putExtra("id",sendId);
                intent.putExtra("content",sendContent);
                intent.putExtra("note_time",sendTime);
                intent.putExtra("title",sendTitle);
                startActivityForResult(intent,1);
            }
        });

/*********************************************listView单项长按点击事件(删除记录)*****************************************/
        //列表项点击监听器，长按触发，删除对应内容
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                //对话框
                AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this)
                        .setIcon(R.mipmap.ic_launcher)
                        .setTitle("提示")
                        .setMessage("是否删除该条记录？")
                        .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                //确定要删除的记录是哪一条
                                Record record= (Record) myAdapter.getItem(position);
                                //获取需要删除记录的id
                                int deleteId=record.getId();
                                int flag = DataSupport.delete(Record.class, deleteId);
                                if (flag==1){
                                    init();
                                    showMsg("删除成功");
                                }else {
                                    showMsg("删除失败");
                                }
                            }
                        })
                        .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        });
                dialog=builder.create();
                dialog.show();
                dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK);
                dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
                return true;
            }
        });
/*********************************************个人中心点击事件*****************************************/
        iv_user.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //跳转到个人中心
                Intent intent=new Intent(MainActivity.this, UserActivity.class);
                intent.putExtra("name",name);
                startActivity(intent);
            }
        });

/***********************************************滑动菜单点击事件***********************************************/
        String[] titles = {"个人中心", "删除所有记录","注销账号"};
        ArrayAdapter<String> MenuAdapter = new ArrayAdapter<String>(MainActivity.this,
                android.R.layout.simple_list_item_1, android.R.id.text1, titles);
        listView2.setAdapter(MenuAdapter);
        listView2.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String count=MenuAdapter.getItem(position);
                /*******************个人中心（查询/修改用户信息）****************/
                if (count.equals("个人中心")){
                    Intent intent1=new Intent(MainActivity.this,UserActivity.class);
                    intent1.putExtra("name",name);
                    startActivity(intent1);
                }
                /*************************删除所有记录************************/
                else if (count.equals("删除所有记录")){
                    AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this)
                            .setIcon(R.mipmap.ic_launcher)
                            .setTitle("提示")
                            .setMessage("是否删除所有记录？")
                            .setPositiveButton("删除", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (DataSupport.deleteAll(Record.class,"user_id=?","1")>0){
                                        showMsg("成功删除所有记录");
                                        init();
                                    }else {
                                        showMsg("删除记录失败");
                                    }
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                    dialog=builder.create();
                    dialog.show();
                    dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK);
                    dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
                }
                /*************************注销账号************************/
                else if (count.equals("注销账号")){
                    AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this)
                            .setIcon(R.mipmap.ic_launcher)
                            .setTitle("提示")
                            .setMessage("是否注销账号？")
                            .setPositiveButton("注销", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (delete()==true){
                                        showMsg("注销成功");
                                        finish();
                                    }else {
                                        showMsg("注销失败");
                                        dialog.dismiss();
                                    }
                                }
                            })
                            .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    dialog.dismiss();
                                }
                            });
                    dialog=builder.create();
                    dialog.show();
                    dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.BLACK);
                    dialog.getButton(DialogInterface.BUTTON_NEGATIVE).setTextColor(Color.BLACK);
                }
            }
        });
    }

    /***********************************************注销账号方法***********************************************/
    private boolean delete() {
        int i = DataSupport.deleteAll(User.class, "name=?", tv_showName.getText().toString());
        SharedPreferences sp1=getSharedPreferences("data1",MODE_PRIVATE);
        SharedPreferences.Editor editor1=sp1.edit();
        editor1.clear();
        boolean flag1=false;
        flag1=editor1.commit();
        if (i>0&&flag1==true){
            return true;
        }else {
            return false;
        }
    }
    private void init() {
        iv_add=findViewById(R.id.iv_add);
        iv_user=findViewById(R.id.iv_user);
        listView=findViewById(R.id.listview);
        listView2=findViewById(R.id.listView2);
        tv_showName=findViewById(R.id.tv_showName);
        if (resultList!=null){
            resultList.clear();
        }
        User user= DataSupport.find(User.class,userId);
        resultList = user.getRecordLists();
        Log.i(TAG, "init: "+resultList.size());
        //适配器
        myAdapter=new MyAdapter(resultList,MainActivity.this);
        listView.setAdapter(myAdapter);
    }
//数据回传时自动调用执行的方法，用于接收回传过来的数据
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1&&resultCode==2){
            //说明数据的添加操作时正常执行的,数据库就新增了一条记录，主页中的ListView的内容就应该更新。
            init();
        }
    }
    //Toast
    private void showMsg(String s) {
        Toast.makeText(MainActivity.this,s,Toast.LENGTH_SHORT).show();
    }
}
